//
//  BMSPrivacyPopupView.m
//  WDBMS
//
//  Created by YeJary on 2025/5/12.
//

#import "BMSPrivacyPopupView.h"
#import <Masonry/Masonry.h>
#import "BMSPopupQueueManager.h"
#import <SafariServices/SafariServices.h>
#import "BMSPrivacyExitView.h"
#import "BMSRealnamePopupView.h"
#import "BMSPrivate.h"
#import "BMSInitializer.h"
#import "BMSLinkOpener.h"
#import "BMSAppInfoHelper.h"
#import "BMSLifecycleManager.h"
@interface BMSPrivacyPopupView()


@end

@implementation BMSPrivacyPopupView {
    UIView *_contentView;
    UILabel *_titleLabel;
    UITextView *_textView;
    UIButton *_agreeBtn;
    UIButton *_disagreeBtn;
    UIView *_maskView;
}

- (instancetype)init {
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self) {
//        self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        [self setupViews];

        // 支持屏幕旋转
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(onScreenRotate)
                                                     name:UIApplicationDidChangeStatusBarOrientationNotification
                                                   object:nil];
    }
    [[BMSOpMergeReporter shared]addEvent:[BMSOpMergeEventBuilder event_userActionWithAct:BMS_EVENT_BASE_PRIVACY description:BMS_WDS_PRIVACY_POPUP_SHOW tab1:@"" tab2:@"" tab3:@"" tabN:@{}]];
    return self;
}

- (void)onScreenRotate {
    self.frame = [UIScreen mainScreen].bounds;

    // 这里是强制刷新约束
    [self setNeedsUpdateConstraints];
    [self layoutIfNeeded];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)setupViews {
    self.userInteractionEnabled = YES;

    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = UIColor.whiteColor;
    _contentView.layer.cornerRadius = 14;
    [self addSubview:_contentView];

    // 标题
    _titleLabel = [[UILabel alloc] init];
    _titleLabel.text = @"用户协议和隐私政策";
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [_contentView addSubview:_titleLabel];

    // 正文
    _textView = [[UITextView alloc] init];
    _textView.editable = NO;
    _textView.scrollEnabled = YES;
    _textView.showsVerticalScrollIndicator = NO;
    _textView.textContainerInset = UIEdgeInsetsZero;
    _textView.textContainer.lineFragmentPadding = 0;
    _textView.delegate = (id<UITextViewDelegate>)self;
    [_contentView addSubview:_textView];

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    style.lineSpacing = 4;
    style.alignment = NSTextAlignmentLeft;

    NSString *text = @"欢迎使用本游戏。我们非常重视您的个人信息和隐私保护。在您使用本游戏前，请仔细阅读《用户协议》和《隐私政策》内容。如您已详细阅读并同意，请点击“同意”开始使用我们的产品和服务；如您不同意，将无法进行游戏。";
    NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithString:text attributes:@{
        NSFontAttributeName: [UIFont systemFontOfSize:14],
        NSForegroundColorAttributeName: UIColor.blackColor,
        NSParagraphStyleAttributeName: style
    }];
    NSString *termUrl = [BMSInitializer shared].launchModel.termUrl.length > 0
                        ? [BMSInitializer shared].launchModel.termUrl
                        : [BMSAppInfoHelper BMSJSONFileFromtermUrl];
    
    NSString *privacyUrl = [BMSInitializer shared].launchModel.privacyUrl.length > 0 ? [BMSInitializer shared].launchModel.privacyUrl : [BMSAppInfoHelper BMSJSONFileFromPrivacyUrl];
    NSRange userRange = [text rangeOfString:@"《用户协议》"];
    NSRange privacyRange = [text rangeOfString:@"《隐私政策》"];
    
    if (userRange.location != NSNotFound) {
        [attrStr addAttribute:NSLinkAttributeName value:termUrl range:userRange];
        [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.systemBlueColor range:userRange];
    }
    if (privacyRange.location != NSNotFound) {
        [attrStr addAttribute:NSLinkAttributeName value:privacyUrl range:privacyRange];
        [attrStr addAttribute:NSForegroundColorAttributeName value:UIColor.systemBlueColor range:privacyRange];
    }
    _textView.attributedText = attrStr;

    // 不同意按钮
    _disagreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_disagreeBtn setTitle:@"不同意" forState:UIControlStateNormal];
    [_disagreeBtn setTitleColor:UIColor.grayColor forState:UIControlStateNormal];
    _disagreeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    _disagreeBtn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1.0];
    _disagreeBtn.layer.cornerRadius = 6;
    [_disagreeBtn addTarget:self action:@selector(onDisagree) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_disagreeBtn];

    // 同意按钮
    _agreeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_agreeBtn setTitle:@"同意" forState:UIControlStateNormal];
    [_agreeBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    _agreeBtn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
    _agreeBtn.backgroundColor = UIColor.systemBlueColor;
    _agreeBtn.layer.cornerRadius = 6;
    [_agreeBtn addTarget:self action:@selector(onAgree) forControlEvents:UIControlEventTouchUpInside];
    [_contentView addSubview:_agreeBtn];

    // 添加布局
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.mas_centerX);
        make.centerY.equalTo(self.mas_centerY);
        make.width.greaterThanOrEqualTo(@300);
        make.width.lessThanOrEqualTo(self.mas_width).multipliedBy(0.9);
        make.width.lessThanOrEqualTo(@400);
        make.height.lessThanOrEqualTo(self.mas_height).multipliedBy(0.95);
//        make.height.lessThanOrEqualTo(@500);
    }];

    [_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_contentView.mas_top).offset(20);
        make.left.right.equalTo(_contentView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
        make.height.mas_equalTo(24);
    }];

    [_textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.mas_bottom).offset(12);
        make.left.right.equalTo(_contentView).insets(UIEdgeInsetsMake(0, 16, 0, 16));
        make.height.greaterThanOrEqualTo(@80); // 推荐加这个
        make.height.lessThanOrEqualTo(@160);   // 限制最大高度
    }];

    [_disagreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_textView.mas_bottom).offset(20);
        make.left.equalTo(_contentView.mas_left).offset(16);
        make.height.mas_equalTo(44);
        make.bottom.equalTo(_contentView.mas_bottom).offset(-16);
    }];

    [_agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.height.equalTo(_disagreeBtn);
        make.left.equalTo(_disagreeBtn.mas_right).offset(12);
        make.right.equalTo(_contentView.mas_right).offset(-16);
        make.width.equalTo(_disagreeBtn);
    }];
}

#pragma mark - Interaction

- (void)onAgree {
    [NSUserDefaults.standardUserDefaults setBool:YES forKey:kBMSKeyPrivacyAgreed];
//    [BMSLifecycleManager isFirstEffectiveLaunch];
    if (self.completion) {
        BOOL agreed = YES;
        [[BMSPopupQueueManager sharedManager] dismissCurrentPopupWithCompletion:^{
            self.completion(agreed);
        }];
    } else {
        [[BMSPopupQueueManager sharedManager] dismissCurrentPopup];
    }
}

- (void)onDisagree {
    [NSUserDefaults.standardUserDefaults setBool:NO forKey:kBMSKeyPrivacyAgreed];
    if (self.completion) self.completion(NO);

    
}

#pragma mark - Show / Dismiss

- (void)showWithCompletion:(BMSPrivacyDecisionHandler)completion {
    BMSPrivacyPopupView *popup = [[BMSPrivacyPopupView alloc] init];
    
}

- (void)dismiss {
//    BMSPrivacyPopupView *popup = [[BMSPrivacyPopupView alloc] init];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView
shouldInteractWithURL:(NSURL *)URL
         inRange:(NSRange)characterRange
     interaction:(UITextItemInteraction)interaction
{
    if ([URL.absoluteString containsString:@"http://"] ||
        [URL.absoluteString containsString:@"https://"]) {

        [BMSLinkOpener openURL:URL.absoluteString];
        NSLog(@"跳转链接：%@", URL);
        return NO; // ✅ 阻止系统默认行为（跳 Safari）
    }

    return NO;
}

#pragma mark --------- safariServices ------------

- (void)openProtocolURL:(id)urlObject from:(UIViewController *)vc {
    if ([urlObject isKindOfClass:[NSString class]]) {
        urlObject = [NSURL URLWithString:(NSString *)urlObject];
    }
    if (![urlObject isKindOfClass:[NSURL class]]) {
        NSLog(@"[BMS] 无效协议链接类型: %@", urlObject);
        return;
    }

    NSURL *url = (NSURL *)urlObject;
    if (!url || !url.scheme || ![url.scheme hasPrefix:@"http"]) {
        NSLog(@"[BMS] URL 无效或不支持: %@", url);
        return;
    }

    SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:url];
    safariVC.modalPresentationStyle = UIModalPresentationPageSheet;
    [vc presentViewController:safariVC animated:YES completion:nil];
}


@end
